<script>
  import KnowledgeForm from "./KnowledgeForm.svelte";
  import KnowledgeView from "./KnowledgeView.svelte";
  import BaseButton from "$lib/components/common/BaseButton.svelte";

  // 从外部接收数据
  export let data = [];

  // 知识库列表数据 - 现在从外部传入
  let knowledgeList = [];

  // 响应式更新内部数据
  $: knowledgeList = data;

  let currentKnowledge = null;
  let isEditing = false;
  let isAdding = false;

  // 使用对象管理表单数据
  let formData = {
    knowledgeName: "",
    ragflowIds: [""],
    searchKeyword: "",
    apiKey: "",
    citationUrl: "",
    thirdPartyWhitelist: false,
    userWhitelist: false,
    departmentWhitelist: false,
    maxBlocks: 15,
    relevanceThreshold: 0.5,
    weightSort: 0.3,
  };

  function addKnowledge() {
    isAdding = true;
    isEditing = true;
    currentKnowledge = null;
    resetForm();
  }

  function resetForm() {
    formData = {
      knowledgeName: "",
      ragflowIds: [""],
      searchKeyword: "",
      apiKey: "",
      citationUrl: "",
      thirdPartyWhitelist: false,
      userWhitelist: false,
      departmentWhitelist: false,
      maxBlocks: 15,
      relevanceThreshold: 0.5,
      weightSort: 0.3,
    };
  }

  function handleEdit(event) {
    const knowledge = event.detail;
    isEditing = true;
    isAdding = false;
    currentKnowledge = knowledge;
    loadKnowledgeData(knowledge);
  }

  function loadKnowledgeData(knowledge) {
    formData = {
      knowledgeName: knowledge.knowledgeName,
      ragflowIds: [...knowledge.ragflowIds],
      searchKeyword: knowledge.searchKeyword,
      apiKey: knowledge.apiKey,
      citationUrl: knowledge.citationUrl,
      thirdPartyWhitelist: knowledge.thirdPartyWhitelist,
      userWhitelist: knowledge.userWhitelist,
      departmentWhitelist: knowledge.departmentWhitelist,
      maxBlocks: knowledge.maxBlocks,
      relevanceThreshold: knowledge.relevanceThreshold,
      weightSort: knowledge.weightSort,
    };
  }

  function handleSave(event) {
    const submitData = event.detail;

    try {
      if (isAdding) {
        const newKnowledge = {
          id: Date.now(),
          name: submitData.knowledgeName || "新知识库",
          ...submitData,
        };
        knowledgeList = [...knowledgeList, newKnowledge];
        console.log("添加知识库", newKnowledge);
      } else {
        knowledgeList = knowledgeList.map((item) =>
          item.id === currentKnowledge?.id
            ? {
                ...item,
                name: submitData.knowledgeName || item.name,
                ...submitData,
              }
            : item
        );
        console.log("保存配置", submitData);
      }

      isEditing = false;
      isAdding = false;
      currentKnowledge = null;
    } catch (error) {
      console.error("保存失败:", error);
    }
  }

  function handleCancel() {
    isEditing = false;
    isAdding = false;
    currentKnowledge = null;
    console.log("取消编辑");
  }

  function handleDelete(event) {
    const knowledge = event.detail;
    if (confirm(`确定要删除知识库"${knowledge.name}"吗？`)) {
      try {
        knowledgeList = knowledgeList.filter(
          (item) => item.id !== knowledge.id
        );
        console.log("删除知识库", knowledge);
      } catch (error) {
        console.error("删除失败:", error);
      }
    }
  }
</script>

<div class="knowledge-config">
  <div class="header">
    <h1>知识库配置</h1>
    <div class="add-btn-container">
      <BaseButton variant="primary" disabled={isAdding} on:click={addKnowledge}>
        <svg
          slot="icon"
          width="16"
          height="16"
          viewBox="0 0 16 16"
          fill="currentColor"
        >
          <path
            d="M7.33398 7.83398V3.83398H8.66732V7.83398H12.6673V9.16732H8.66732V13.1673H7.33398V9.16732H3.33398V7.83398H7.33398Z"
          />
        </svg>

        添加知识库
      </BaseButton>
    </div>
  </div>

  <div class="knowledge-list">
    {#if knowledgeList.length === 0 && !isAdding}
      <div class="empty-state">
        <div class="empty-icon">📚</div>
        <h3>暂无知识库</h3>
        <p>点击右上角"添加知识库"按钮创建您的第一个知识库</p>
      </div>
    {:else}
      <!-- 添加表单 -->
      {#if isAdding}
        <KnowledgeForm
          mode="add"
          title="新建知识库"
          bind:formData
          on:save={handleSave}
          on:cancel={handleCancel}
        />
      {/if}

      <!-- 编辑表单 -->
      {#if isEditing && !isAdding}
        <KnowledgeForm
          mode="edit"
          title="编辑 {currentKnowledge?.name || ''}"
          knowledge={currentKnowledge}
          bind:formData
          on:save={handleSave}
          on:cancel={handleCancel}
        />
      {/if}

      <!-- 知识库列表 -->
      {#each knowledgeList as knowledge (knowledge.id)}
        {#if !isEditing || currentKnowledge?.id !== knowledge.id}
          <KnowledgeView
            {knowledge}
            disabled={isAdding}
            on:edit={handleEdit}
            on:delete={handleDelete}
          />
        {/if}
      {/each}
    {/if}
  </div>
</div>

<style>
  .knowledge-config {
    max-width: 1200px;
    margin: 0 auto;
    padding: 24px;
    background-color: #fff;
  }

  .header {
    padding: 12px 12px;
    text-align: center;
  }

  .header h1 {
    font-weight: bolder;
    font-size: 16px;
    color: rgba(36, 36, 36, 1);
  }

  .add-btn-container {
    display: flex;
    justify-content: flex-end;
  }

  .empty-state {
    text-align: center;
    padding: 80px 40px;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-radius: 20px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
  }

  .knowledge-list {
    padding: 8px 12px;
    border: 1px solid rgba(239, 239, 246, 1);
    background-color: rgba(250, 250, 255, 1);
  }

  .empty-icon {
    font-size: 64px;
    margin-bottom: 24px;
    opacity: 0.8;
  }

  .empty-state h3 {
    font-size: 24px;
    font-weight: 600;
    margin: 0 0 12px 0;
    color: #333;
  }

  .empty-state p {
    margin: 0;
    color: #666;
    font-size: 16px;
    line-height: 1.5;
  }
</style>
    
